package com.lywz.core.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.springframework.orm.hibernate3.LocalSessionFactoryBean;

import com.lywz.core.entity.EntityAnnotation;
import com.lywz.core.log.LogClerk;
import com.lywz.core.util.PackageUtil;

/**
 * 自定义spring工厂
 * 
 * @author Lionel
 * @since 1.0.0
 * 
 */
public class HibernateSessionFactoryBean extends LocalSessionFactoryBean {

    // hibernate配置
    private static AnnotationConfiguration config;

    private static String configFilePath = "hibernate.cfg.xml";

    /**
     * 锁对象
     */
    private Object lockObj = new Object();
    
    /**
     * 覆盖父类的获取配置方法。获取自己创建的配置。
     */
    protected Configuration newConfiguration() throws HibernateException {
        if (config == null) {
            synchronized (lockObj) {
                if (config == null) {
                    config = new AnnotationConfiguration();
                    config.configure(configFilePath);
                   /* try {
                        addConfig(config);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                        LogClerk.sysout.error("scan hibernate entity error", e);
                    }*/
                }
            }
        }

        return config;
    }

    /*protected SessionFactory buildSessionFactory() throws Exception {
    	return null;// super.buildSessionFactory();
    }*/

    @SuppressWarnings( { "unchecked", "static-access" })
    public static void addConfig(AnnotationConfiguration config) throws ClassNotFoundException {
        LogClerk.sysout.info("begin to scan the annotation class");
        List<String> cls = PackageUtil.getClassInPackage("com.lywz.biz.common.entity");
        for (String s : cls) {
            Class cla = Class.class.forName(s);
            if (!cla.isAnnotationPresent(EntityAnnotation.class)) {
                continue;
            }
            
            config.addAnnotatedClass(cla);
        }
        
        LogClerk.sysout.info("scan the annotation class end");
    }
}
